<template>
    <div class="app-container">
    <el-row :gutter="5">
        <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="mini">添加</el-button>
        </el-col>
        <el-col :span="1.5">
            <el-button icon="el-icon-delete" type="danger" @click="handleDelete" size="mini">删除选中</el-button>
        </el-col>
    </el-row>
    <el-table
            :data="tableData"
            stripe
            border
            row-key="menuId"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            @selection-change="handleSelectionChange"
            style="width: 100%"
            :cell-style="{padding:'3px'}"
    >
        <el-table-column type="selection" width="55"></el-table-column>
<!--        <el-table-column prop="parentId" label="父菜单id" width="80"></el-table-column>-->
<!--        <el-table-column prop="menuId" label="菜单id" width="80"></el-table-column>-->
        <el-table-column prop="menuName" label="菜单名称" width="160"></el-table-column>
        <el-table-column prop="orderNum" label="显示顺序"></el-table-column>
        <el-table-column prop="menuType" label="菜单类型" :formatter="formatMenuType" width="80"></el-table-column>
        <el-table-column prop="path" label="路由path"></el-table-column>
        <el-table-column prop="component" label="组件名称" width="160"></el-table-column>
        <el-table-column prop="apiUrl" label="接口地址" width="160"></el-table-column>
        <el-table-column prop="httpMethod" label="HTTP方法"></el-table-column>
        <el-table-column prop="visible" label="是否可见">
            <template slot-scope="scope">
                <el-tag :type="scope.row.visible === '0' ? 'success' : 'danger'">
                    {{scope.row.visible === '0' ? '是' : '否'}}
                </el-tag>
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160">
            <template slot-scope="scope">
                <el-tooltip content="修改" placement="top">
                    <el-button @click="handleEdit(scope.row)" type="primary" size="small" icon="el-icon-edit" circle></el-button>
                </el-tooltip>
                <el-tooltip content="删除" placement="top">
                    <el-button @click="handleDeleteRow(scope.row)" type="danger" size="small" icon="el-icon-delete" circle></el-button>
                </el-tooltip>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination
            layout="total, prev, pager, next"
            v-show="total>0"
            :total="total"
            :page-size="queryParams.limit"
            @current-change="handleCurrentChange">
    </el-pagination>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="父菜单" prop="parentId">
                        <treeselect placeholder="默认：根菜单" v-model="form.parentId" :normalizer="normalizer" :options="menuOptions" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="菜单类型" prop="menuType">
                        <el-radio-group @click="handleMenuTypeChange" v-model="form.menuType">
                            <el-radio v-for="item in menuType" :key="item.value" :label="item.value">{{item.label}}</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="菜单名称" prop="menuName">
                        <el-input v-model="form.menuName" placeholder="例如：用户管理" maxlength="20" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.menuId">
                    <el-form-item label="菜单排序" prop="orderNum">
                        <el-input type="number" v-model="form.orderNum" placeholder="请输入菜单排序" maxlength="20" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.menuType == 'C'">
                    <el-form-item label="vue路由path" prop="path">
                        <el-input v-model="form.path" placeholder="例如：users" maxlength="20" />
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.menuType != 'F'">
                    <el-form-item label="是否可见" prop="visible">
                        <el-radio v-model="form.visible" label="0">可见</el-radio>
                        <el-radio v-model="form.visible" label="1">隐藏</el-radio>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="!form.menuId && form.menuType =='M'">
                    <el-form-item label="" prop="restful">
                        <el-checkbox v-model="form.restful">生成增删改查</el-checkbox>
                    </el-form-item>
                </el-col>
                <el-col :span="24" v-if="form.menuType != 'M'">
                    <el-form-item label="HTTP方法" prop="httpMethod">
                        <!--<el-select v-model="form.httpMethod" multiple placeholder="请选择">
                            <el-option
                                    v-for="item in httpMethod"
                                    :key="item"
                                    :value="item">
                            </el-option>
                        </el-select>-->
                        <el-radio v-model="form.httpMethod" label="GET">GET</el-radio>
                        <el-radio v-model="form.httpMethod" label="POST">POST</el-radio>
                        <el-radio v-model="form.httpMethod" label="PUT">PUT</el-radio>
                        <el-radio v-model="form.httpMethod" label="DELETE">DELETE</el-radio>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.menuType != 'M' || form.restful">
                    <el-form-item label="后端api地址" prop="apiUrl">
                        <el-input v-model="form.apiUrl" placeholder="例如/users" maxlength="20"/>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="form.menuType == 'C' || form.restful">
                    <el-form-item label="组件地址" title="前端路由/页面的地址" prop="component">
                        <el-input v-model="form.component" placeholder="例如system/user/index.vue" maxlength="30" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
        </div>
    </el-dialog>
    </div>
</template>
<script>
    import {del,get,add,update,listAll} from "@/api/system/menu";
    import Treeselect from "@riophae/vue-treeselect";
    import "@riophae/vue-treeselect/dist/vue-treeselect.css";
    export default {
        name: "Menu",
        components: { Treeselect },
        data() {
            return {
                queryParams: {
                    page: 1,
                    limit: 10
                },
                total: 0,
                totalPageCount: 0,
                tableData: [],
                multipleSelection: [],
                title: '',
                menuOptions: [],
                // 添加/修改表单参数
                menuType:[{label:'菜单',value:'M'},{label:'组件',value:'C'},{label:'按钮',value:'F'}],
                /*httpMethod:['GET','POST','PUT','DELETE'],*/
                form: {
                },
                // 添加/修改表单校验
                rules: {
                    menuName: [
                        {required: true, message: "菜单名称不能为空", trigger: "blur"}
                    ],
                   /* parentId: [
                        {required: true, message: "父菜单不能为空", trigger: "blur"}
                    ],*/
                    apiUrl: [
                        {required: true, message: "接口地址不能为空", trigger: "blur"}
                    ],
                    httpMethod: [
                        {required: true, message: "HTTP方法不能为空", trigger: "blur"}
                    ],
                    menuType: [
                        {required: true, message: "菜单类型不能为空", trigger: "blur"}
                    ],
                    component: [
                        {required: true, message: "组件路径不能为空", trigger: "blur"}
                    ],
                    orderNum: [
                        {required: true, message: "菜单排序不能为空", trigger: "blur"}
                    ],
                    path: [
                        {required: true, message: "路由路径不能为空", trigger: "blur"}
                    ],
                },
                // 是否显示弹出层
                open: false,
            }
        },
        created() {
            this.getList()
        },
        watch: {
            // 删除最后一页所有数据时，回到上一页
            total(val) {
                if(val == (this.queryParams.page-1) * this.queryParams.limit){
                    this.queryParams.page--
                    this.getList()
                }
            }
        },
        methods: {
            formatMenuType(row) {
                if(row.menuType === 'M') {
                    return '菜单'
                } else if(row.menuType === 'C') {
                    return '组件'
                } else if(row.menuType === 'F') {
                    return '按钮'
                } else {
                    return '未知'
                }
            },
            // 取消按钮
            cancel() {
                this.open = false;
                this.reset();
            },
            reset() {
                this.form = {
                    menuId: undefined,
                    menuName: undefined,
                    menuType: 'M',
                    orderNum: undefined,
                    apiUrl: undefined,
                    component: undefined,
                    visible: '0',
                    httpMethod: undefined,
                    parentId: undefined,
                    restful: false,
                    path: undefined,
                }
            },
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if(valid) {
                        if(this.form.menuId != undefined) {
                            update(this.form).then(()=>{
                                this.$message({message:'修改成功', type:'success'})
                                this.open = false
                                this.getList()
                            })
                        } else {
                            add(this.form).then(()=>{
                                this.$message({message:'添加成功', type:'success'})
                                this.open = false
                                this.getList()
                            })
                        }
                    }
                })
            },
            getList() {
                /*list(this.queryParams).then(response => {
                    this.tableData = this.handleTree(response.data.records, "menuId")
                    this.total = response.data.total
                })*/
                listAll().then(response => {
                    this.tableData = this.handleTree(response.data, "menuId")
                })
            },
            handleMenuTypeChange() {
                this.$refs["form"].resetFields()
            },
            handleSelectionChange(val) {
                this.multipleSelection = val
            },
            handleCurrentChange(val) {
                this.queryParams.page = val;
                this.getList()
            },
            handleAdd() {
                this.reset();
                this.open = true;
                this.title = "添加菜单";
                listAll().then(response=>{
                    this.menuOptions = this.handleTree(response.data, "menuId")
                })
            },
            /** 转换部门数据结构 */
            normalizer(node) {
                if (node.children && !node.children.length) {
                    delete node.children;
                }
                return {
                    id: node.menuId,
                    label: node.menuName,
                    children: node.children
                };
            },
            handleView(row) {
                get(row.menuId).then(resp=>{
                    console.log(resp);
                })
            },
            handleEdit(row) {
                this.reset();
                listAll().then(response=>{
                    this.menuOptions = this.handleTree(response.data, "menuId")
                })
                get(row.menuId).then(resp=>{
                    this.form = resp.data;
                    if(this.form.parentId==0) this.form.parentId = null
                    this.open = true;
                    this.title = "修改菜单";
                })
            },
            handleDeleteRow(row) {
                this.$confirm('确定删除"' + row.menuName + '"吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    let idList = row.menuId;
                    del(idList).then(resp => {
                        this.$message({
                            type: 'success',
                            message: resp.msg
                        });
                        this.getList()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            handleDelete() {
                if(this.multipleSelection.length == 0) {
                    this.$alert('请至少选中一条记录')
                } else {
                    this.$confirm('确定删除选中的记录吗, 是否继续?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let idList = this.multipleSelection.map(row=>row.menuId).join(",");
                        del(idList).then(resp => {
                            this.$message({
                                type: 'success',
                                message: resp.msg
                            });
                            this.getList()
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        });
                    });
                }
            },
            handleStatusChange(row) {
                let text = row.status === "0" ? "启用" : "停用";
                this.$confirm('确认要"' + text + '""' + row.menuName + '"菜单吗?', "警告", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(function() {
                    return update({deptId:row.menuId, status:row.status});
                }).then(() => {
                    this.$message(text + "成功");
                }).catch(function() {
                    row.status = row.status === "0" ? "1" : "0";
                });
            }
        }
    }
</script>
